package com.cj.common.config.handerconfig;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Author cheng jun
 * @Description:
 * @Date 2021/7/13 18:02
 */

/**
 * 支持Nacos的动态刷新功能
 */
@RefreshScope
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    @Value("${org.my.jwt.jwt-header-name}")
    private String jwtHeaderName;

    @Value("${org.my.jwt.jwt-header}")
    private String jwtHeader;

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null != attributes) {
            HttpServletRequest request = attributes.getRequest();
            // 获取request请求头信息，传递给下一层
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    template.header(name, values);
                }
            }
        }
        // 独立设置参数
        template.header(jwtHeaderName, jwtHeader);
    }
}
